// API基础配置
const API_BASE_URL = process.env.NODE_ENV === 'production' 
  ? '/api'  // 生产环境使用相对路径
  : 'http://localhost:3000/api';  // 开发环境使用完整URL

// 通用请求方法
async function request(url, options = {}) {
  const token = localStorage.getItem('token');
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` })
    }
  };

  const config = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers
    }
  };

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config);
    const data = await response.json();
    
    if (!response.ok) {
      throw new Error(data.error || '请求失败');
    }
    
    return data;
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
}

// 用户相关API
export const userAPI = {
  // 用户登录
  login: (username, password) => {
    return request('/users/login', {
      method: 'POST',
      body: JSON.stringify({ username, password })
    });
  },

  // 用户注册
  register: (userData) => {
    return request('/users/register', {
      method: 'POST',
      body: JSON.stringify(userData)
    });
  },

  // 获取用户信息
  getProfile: () => {
    return request('/users/profile');
  },

  // 修改密码
  changePassword: (username, oldPassword, newPassword) => {
    return request('/users/change-password', {
      method: 'POST',
      body: JSON.stringify({ username, oldPassword, newPassword })
    });
  },

  // 获取用户列表（管理员）
  getUsers: () => {
    return request('/users');
  }
};

// 样品相关API
export const sampleAPI = {
  // 获取样品列表
  getSamples: (keyword = '') => {
    const url = keyword ? `/samples?keyword=${encodeURIComponent(keyword)}` : '/samples';
    return request(url);
  },

  // 获取单个样品
  getSample: (id) => {
    return request(`/samples/${id}`);
  },

  // 创建样品
  createSample: (sampleData) => {
    return request('/samples', {
      method: 'POST',
      body: JSON.stringify(sampleData)
    });
  },

  // 更新样品
  updateSample: (id, sampleData) => {
    return request(`/samples/${id}`, {
      method: 'PUT',
      body: JSON.stringify(sampleData)
    });
  },

  // 删除样品
  deleteSample: (id) => {
    return request(`/samples/${id}`, {
      method: 'DELETE'
    });
  }
};

// 工具方法
export const apiUtils = {
  // 检查用户是否已登录
  isLoggedIn: () => {
    return !!localStorage.getItem('token');
  },

  // 获取当前用户信息
  getCurrentUser: () => {
    const userStr = localStorage.getItem('user');
    return userStr ? JSON.parse(userStr) : null;
  },

  // 登出
  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  },

  // 设置认证信息
  setAuth: (token, user) => {
    localStorage.setItem('token', token);
    localStorage.setItem('user', JSON.stringify(user));
  }
}; 